#include "sourcemanager.h"

SourceManager::SourceManager(QObject *parent)
	: QObject(parent)
{
	start = true;
}

SourceManager::SourceManager(QString &source, QObject *parent)
	: QObject(parent)	
{
	code = source.split('\n', QString::KeepEmptyParts);//, /*QString::SkipEmptyParts*/);

	for(int i = 0; i < code.size(); ++i)
	{
		code[i].append(' ');
	}

	start = true;
}

SourceManager::~SourceManager()
{

}

void SourceManager::setSource(QString &source)
{
	system("cls");
	code = source.split('\n', QString::KeepEmptyParts);

	for(int i = 0; i < code.size(); ++i)
	{
		code[i].append(' ');
	}

	curr_pos.reset();
	start = true;
	//nextLine();
	//test();
}

TextPosition SourceManager::position()
{
	return curr_pos;
}

char SourceManager::nextChar()
{	
	if(start)
	{
		if( !nextLine() ) return 0;;		
		//qDebug() << code[curr_pos.row()].at(curr_pos.at());
		qint32 size = code.size();
		if(!code.isEmpty())
		{
			if(code[curr_pos.row()].size() == curr_pos.at())
			{
				if( !nextLine() )				// wczytanie kolejnej linii		
				{
					qDebug() << "koniec";
					return 0;					// jesli to koniec return EOF
				}
			}
			return code[curr_pos.row()].at(curr_pos.at()).toAscii();
		}
		else
		{
			qDebug() << "koniec";
			return 0;					// jesli to koniec return EOF
		}		
	}	

	// przesuwamy sie z pozycja na nastepny znak
	curr_pos.toNextChar();

	// jesli to juz koniec linii to nastepny znak
	if(code[curr_pos.row()].size() == curr_pos.at())
	{
		if( !nextLine() )				// wczytanie kolejnej linii		
		{
			qDebug() << "koniec";
			return 0;					// jesli to koniec return EOF
		}
	}	
	//qDebug() << code[curr_pos.row()].at(curr_pos.at());
	return code[curr_pos.row()].at(curr_pos.at()).toAscii();
}

bool SourceManager::nextLine()
{
	
	if( !start )
	{
		curr_pos.toNextRow();
		if(curr_pos.row() == code.size())	// jesli to koniec pliku zrodlowego
		{
			//qDebug() << "To by bylo na tyle...";
			return false;
		}
	}else
	{
		qDebug() << "start()";
		start = false;//curr_pos.reset_at();
	}
	
	//qDebug() << "nextLine()";

	while((code[curr_pos.row()].at(curr_pos.at()) == ' ' ||
		   code[curr_pos.row()].at(curr_pos.at()) == '\t' ))		// wywal znaki biale
	{
		curr_pos.toNextChar();
		if(code[curr_pos.row()].size() == curr_pos.at())		// jak wychodzimy za linie
			return nextLine();									// wczytac nastepna
	}
	return true;
}

void SourceManager::test()
{
	qDebug() << "Test:";
	while(nextChar()){}
	qDebug() << "Kuniec";
}